const execa = require("execa");

class ProcessMainWindow {
    constructor(registerCallback) {
        this.child = null;
        this.registerCallback = registerCallback;
    }

    closeMainWindow() {
        try {
            if (!this.child) return false;
            this.child.kill(9);
            this.child = null;
        } catch (e) {
            console.error("clsoe electron main window is fail...", e);
        }
    }

    apply(compiler) {
        compiler.hooks.thisCompilation.tap(
            "defineElectronPlugin",
            this.registerCompilationHooks.bind(this)
        );

        compiler.hooks.done.tapAsync(
            "openElectron",
            this.buildDownElectron.bind(this)
        );

        compiler.hooks.shutdown.tapAsync(
            "shutdownMainProcess",
            this.shutdownMainProcess.bind(this)
        );
    }

    shutdownMainProcess(callback) {
        this.closeMainWindow();
        callback();
    }

    buildDownElectron(_, callback) {
        callback();
        if (this.child) return false;
        this.child = execa("electron", ["."], {
            cwd: "./",
            env: {
                electron_dev_host: "127.0.0.1",
                electron_dev_port: "3008",
            },
        });

        this.child.stdout.pipe(process.stdout);
        this.child.stderr.pipe(process.stderr);
        this.child.addListener("exit", this.closeMainWindow);
        this.child.addListener("error", this.closeMainWindow);
        this.child.addListener("close", this.closeMainWindow);
    }

    registerCompilationHooks(compilation) { }
}

module.exports = ProcessMainWindow;
